﻿using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using Random = UnityEngine.Random;
using WeiMiao;

namespace Code0914
{
    public class Random_Panel : MonoBehaviour
    {
        [Header("几何嵌板数组")]
        public GameObject[] panel_gameObjects; // panel 物体数组

        [Header("游戏是否胜利")]
        public bool isVictory = false;

        private static Random_Panel instance;

        private void Awake()
        {
            instance = this;
        }

        // Start is called before the first frame update
        void Start()
        {
            
            // 顺序数组
            int[] nums = new int[panel_gameObjects.Length];

            for (int i = 0; i < panel_gameObjects.Length; i++)
            {
                nums[i] = i;
            }

            // 打乱顺序数组的顺序
            GetDisorderInt(nums);

            List<Vector3> origin_panel_position = new List<Vector3>();
            foreach (GameObject gameObject in panel_gameObjects)
            {
                origin_panel_position.Add(gameObject.transform.position);
            }

            for (int i = 0; i < panel_gameObjects.Length; i++)
            {
                panel_gameObjects[i].transform.position = origin_panel_position[nums[i]];
            }
        }

        // 获取单例
        public static Random_Panel GetInstance()
        {
                return instance;
        }

        // 数组乱序
        void GetDisorderInt(int[] byt)
        {
            int min = 1;
            int max = byt.Length;
            int inx = 0;
            int b = 0;
            System.Random rnd = new System.Random();
            while (min != max)
            {
                int r = rnd.Next(min++, max);
                b = byt[inx];
                byt[inx] = byt[r];
                byt[r] = b;
                inx++;
            }
        }

        // 检测是否胜利
        public void CheckVictory()
        {
            // 匹配个数
            int target_num = 0;

            // 遍历每个 Panel，进行匹配计数
            foreach(GameObject gameObject in panel_gameObjects)
            {
                if(gameObject.GetComponent<Panel>().isTarget)
                {
                    target_num += 1;
                }

                if(target_num == panel_gameObjects.Length)
                {
                    isVictory = true;
                    GameObject.Find("OverallUI").gameObject.GetComponent<UI>().Pass();
                }
                else
                {
                    isVictory = false;
                }
            }
        }
    }
}
